<?php
namespace Xxfaxy\DryBundle\Services;

class Make
{

    protected $container;

    public function __construct($service_container)
    {
        $this->container = $service_container;
    }

    public function makeChoice($choiceConfigKey, $default = '')
    {
        $twig = $this->container->get('twig');
        $crud = $this->container->get('service.crud')->switch2obj();
        $sql = $this->container->get('service.sql');
        $sql1 = $sql->table('dry_choice_config')->where('dry_key', '=', $choiceConfigKey)->get();
        $choiceConfig = $crud->fetch($sql1);
        $temp = explode('@', $choiceConfig->dry_choice);
        if(count($temp) == 2){
            $list = $this->getDataFromTableKeyValue($temp[1]);
        }
        else{
            $sql2 = $sql->table('choice')->where('dryKey', '=', $choiceConfig->dry_choice)->get();
            $choice = $crud->fetch($sql2);
            $list = json_decode($choice->dryValue, true);
        }
        if($default == ''){
            $default = explode(',', $choiceConfig->dry_choice_default);
        }
        else{
            $default = explode(',', $default);
        }
        $data = array(
            'text' => $choiceConfig->dry_form_text,
            'name' => $choiceConfig->dry_form_name,
            'default' => $default,
            'list' => $list
        );
        return $twig->render("XxfaxyDryBundle:_system_/make:{$choiceConfig->dry_form_type}.html.twig", $data);
    }

    public function getDataFromTableKeyValue($alias, $isKeyValue = false)
    {
        $crud = $this->container->get('service.crud')->switch2obj();
        $rs = $crud->fetch("select * from dry_table_key_value where dry_alias='{$alias}'");
        if($rs->dry_sql == ''){
            $list = $crud->fetchAll("select {$rs->dry_key} as k,{$rs->dry_value} as v from {$rs->dry_table} order by {$rs->dry_order}");
        }
        else{
            $list = $crud->fetchAll($rs->dry_sql);
        }
        $result = array();
        foreach($list as $v){
            if($isKeyValue){
                $result[$v->k] = $v->v;
            }
            else{
                $result[] = array(
                    'status' => '1',
                    'key' => $v->k,
                    'value' => $v->v,
                    'note' => ''
                );
            }
        }
        return $result;
    }

}
